package com.easyOrder.callback;

/**
 * Created by liutao on 2017/7/19.
 */

import com.easyOrder.core.mq.Callback;
import com.easyOrder.core.mq.TopicTag;
import com.aliyun.openservices.ons.api.Message;
import com.easyOrder.model.MessageQueueRecord;
import com.easyOrder.model.User;
import com.easyOrder.param.requisition.RequisitionParam;
import com.easyOrder.service.ISequenceService;
import com.easyOrder.service.enums.SeqType;
import com.easyOrder.service.mq.MQRecordService;
import com.easyOrder.service.requisition.RequisitionService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;


public class RequisitionCreatedCallback implements Callback {

    @Autowired
    private MQRecordService mqRecordService;

    @Autowired
    private ISequenceService seqBuilderService;

    @Autowired
    private RequisitionService requisitionService;

    @Override
    public void execute(Message message) {
        String json = new String(message.getBody());
        Type typeToken = new TypeToken<RequisitionParam>() {}.getType();
        RequisitionParam requisition = new Gson().fromJson(json, typeToken);
        mqRecordService.add(requisition.getBranchId(),
                new String(message.getBody()),
                message.getMsgID(),
                requisition.getTenantId(),
                getTag().getValue(),
                requisition.getSession() == null ? null : requisition.getSession().getUserId(),
                requisition.getSession() == null ? null : requisition.getSession().getEmployeeId());
        if (CollectionUtils.isEmpty(requisition.getItems())) {
            return;
        }
        requisition.setId(seqBuilderService.newKey(SeqType.Requisition));
        requisition.getItems().forEach(item -> item.setId(seqBuilderService.newKey(SeqType.RequisitionDetail)));

        requisitionService.add(requisition);
        System.out.println("成功");
    }

    @Override
    public TopicTag getTag() {
        return TopicTag.requisitionCreate;
    }
}

